package com.ruoyi.framework.netty.childhandler.heart;

import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.framework.netty.properties.NettyChatProperties;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;

/**
 * 用于检测channel的心跳handler
 * @author zhusy
 * @since 2021/11/22
 */
public class HeartBeatHandler extends IdleStateHandler {

    /**
     * 设置心跳检测时间
     */
    public HeartBeatHandler() {
        super(SpringUtil.getBean(NettyChatProperties.class).getReadTime(),
                SpringUtil.getBean(NettyChatProperties.class).getWriterTime(),
                SpringUtil.getBean(NettyChatProperties.class).getAllTime(), TimeUnit.SECONDS);
    }

    /**
     * 通道空闲
     * @param ctx 通道上下文对象
     * @param idleStateEvent 事件
     * @throws Exception
     */
    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent idleStateEvent) throws Exception {
        if (idleStateEvent.state() == IdleState.READER_IDLE) {
//            System.out.println("进入读空闲。。。。。。");
        } else if (idleStateEvent.state() == IdleState.WRITER_IDLE) {
//            System.out.println("进入写空闲。。。。。。");
        } else if (idleStateEvent.state() == IdleState.ALL_IDLE) {
//            System.out.println("进入读写空闲。。。。。");
        }
    }

}
